package com.nonagon.melladesk.service;

import com.nonagon.melladesk.service.JwtAuthenticationService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author flitsneak
 * @ClassName
 * @date 2021/3/23 13:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SecurityContextService implements ServerSecurityContextRepository {

    private final JwtAuthenticationService jwtAuthenticationService;

    @Override
    public Mono<Void> save(ServerWebExchange serverWebExchange, SecurityContext securityContext) {
        return Mono.empty();
    }

    @SneakyThrows
    @Override
    public Mono<SecurityContext> load(ServerWebExchange serverWebExchange) {
        //log.info("访问 serversecuritycontext");

        String token = serverWebExchange.getAttribute("token");
        return jwtAuthenticationService
                .authenticate(new UsernamePasswordAuthenticationToken(token,token))
                .map(SecurityContextImpl::new);
    }
}
